#! /usr/bin/env bash

bssid=$1
essid=$2
delay=$3
pause=$4

if [ -z "$bssid" ]
then
	echo Usage: $(basename $0) bssid [essid] [delay] [pause]
	exit
fi

if [ -z "$delay" ]
then
	delay=0
fi

if [ -z "$pause" ]
then
	pause=5
fi

echo $$ >> "$(echo $0 | sed s/\.sh$//).pid"

cd "$(dirname "$0")"
cd ..

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
if [ -n "$essid" ]
then
	identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
fi

cd capture
mkdir -p $identifier
cd $identifier

sleep $delay

korek=0
fudge=2
brute=1

while [ ! -f key.txt ]
do
	source=
	if [ -f capture.ivs ]
	then
		source=capture.ivs
	fi
	if ls -1 ????-??-??-??-??-??-??.cap &> /dev/null
	then
		source="$source $(ls -1 --reverse ????-??-??-??-??-??-??.cap | head --lines 1)"
	fi

	if [ $korek -eq 0 ]
	then
		echo $(date +"%Y-%m-%d %H:%M:%S") Cracking fudge $fudge brute $brute
		echo
		aircrack-ng -K -b $bssid -f $fudge -l key.txt -s $source -x$brute
	else
		echo $(date +"%Y-%m-%d %H:%M:%S") Cracking fudge $fudge brute $brute korek $korek
		echo
		aircrack-ng -K -b $bssid -f $fudge -k $korek -l key.txt -s $source -x$brute
	fi
	echo
	echo

	if [ $korek -lt 17 ]
	then
		korek=$(($korek + 1))
	else
		korek=0

		if [ $brute -lt 2 ]
		then
			brute=$(($brute + 1))
		else
			brute=0

			if [ $fudge -lt 8 ]
			then
				fudge=$(($fudge * 2))
			else
				fudge=2
			fi
		fi
	fi

	sleep $pause
done

